﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
#if DEBUG
using TStudyDigitalPen.HID;
#endif
using TStudyDigitalPen.AP;
namespace MicroTest
{
    public partial class FrmSwhich : Form
    {
#if DEBUG
        private DigitalPenHID digitalPen;
#endif
        private DigitalPenAP digitalPenAp;
        private SceneType enterSceneType;
        private FrmExam frmExam;
        private FrmPrepare frmPrepare;
        private FrmClass frmClass;
        public static FrmSwhich SwhichFrm;
        //private FrmClass frmClass;
        public FrmSwhich(SceneType sentype)
        {
            InitializeComponent();
            enterSceneType = sentype;
            SwhichFrm = this;
#if DEBUG
            digitalPen = DigitalPenHID.GetInstance(certificates.MyLicense.Bytes);
#endif

            digitalPenAp = DigitalPenAP.GetInstance(certificates.MyLicenseAp.Bytes);
        }

        private void FrmSwhich_Load(object sender, EventArgs e)
        {
            
#if DEBUG
            digitalPen.Start();
#endif
            TStudyDigitalPen.AP.ERROR_CODE er = digitalPenAp.Start();

            //if (er != TStudyDigitalPen.AP.ERROR_CODE.ERROR_OK)
            //{
            //    (sender as ImageButton).Enabled = true;
            //    MessageBox.Show("开启失败，错误信息：{0}", er.ToString());
            //    ELogger.Trace(string.Format("开始考试失败，启动AP异常，错误信息：{0}", er.ToString()));
            //    return;
            //}
            switch (enterSceneType)
            {
                case SceneType.Scene_Class:
                    SwichToClass();
                    break;
                case SceneType.Scene_Exam:
                    SwichToExam();
                    break;
                case SceneType.Scene_Prepare:
                case SceneType.Scene_ExamPrepare://考试未检测名单，进入绑定
                case SceneType.Scene_ClassPrepare:

                    SwichToPrepare();
                    break;
                default:
                    break;
            }
#if DEBUG
            digitalPen.PenConnected += DigitalPen_PenConnected;
            digitalPen.PenDisconnect += DigitalPen_PenDisconnect;
            digitalPen.PenCoordinate += DigitalPen_PenCoordinate;
            digitalPen.PenDown += DigitalPen_PenDown;
            digitalPen.PenUp += DigitalPen_PenUp;
#endif

            digitalPenAp.PenConnected += DigitalPen_PenConnected;
            digitalPenAp.PenDisconnect += DigitalPen_PenDisconnect;
            digitalPenAp.PenCoordinate += DigitalPen_PenCoordinate;
            digitalPenAp.PenDown += DigitalPen_PenDown;
            digitalPenAp.PenUp += DigitalPen_PenUp;

            this.BeginInvoke(new Action(() => {
                this.Hide();
                this.Opacity = 1;
            }));
        }
        public void SwichToScene(SceneType st)
        {
            switch (st)
            {
                case SceneType.Scene_Class:
                    SwichToClass();
                    break;
                case SceneType.Scene_Exam:
                    SwichToExam();
                    break;
                case SceneType.Scene_Prepare:
                    SwichToPrepare();
                    break;
                default:
                    break;
            }
            enterSceneType = st;

        }
        public void SwichToClass()
        {
            if (frmClass == null||frmClass.IsDisposed)
                frmClass = new FrmClass();
            frmClass.ResumeMode = ResumeClassData();
            frmClass.Show();
            frmClass.IniClass();
        }
        public SceneType GetSceneType()
        {
            return enterSceneType;
        }
        public void SwichToExam()
        {
            
            if (frmExam == null || frmExam.IsDisposed)
                frmExam = new FrmExam();
            frmExam.ResumeMode = ResumeExamData();
            frmExam.Show();
            frmExam.IniExam();
        }
        public void SwichToPrepare()
        {
            if(frmPrepare == null || frmPrepare.IsDisposed)
            {
                frmPrepare = new FrmPrepare();
            }
            frmPrepare.Show();
        }
        /// <summary>
        /// 恢复考试数据
        /// </summary>
        /// <returns></returns>
        private bool ResumeExamData()
        {
            string dataFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass\\mt.dat";
            bool bNeedResume = false;
            if (File.Exists(dataFile))
            {
                try
                {
                    MicroTestInfo mti = SerializeHelper.DeserialData<MicroTestInfo>(dataFile);
                    if (mti == null || mti.MicroTestRoomInfo != Program.MTInfo.MicroTestRoomInfo)
                        return false;

                    Program.MTInfo = SerializeHelper.DeserialData<MicroTestInfo>(dataFile);
                    bNeedResume = true;
                    ELogger.Trace(string.Format("恢复上次考试数据 考试时间：{0} 班级信息：{1} 考试信息：{2}", Program.MTInfo.MicroTestDate.ToString("yyyy-MM-dd"), Program.MTInfo.MicroTestRoomInfo, Program.MTInfo.MicroTestTitle));
                    for (int i = 0; i < Program.MTInfo.CardList.Count; i++)
                    {
                        ELogger.Trace(string.Format("恢复学生名单 学生{0}：{1}", i + 1, Program.MTInfo.CardList[i].Name));
                    }

                    ELogger.Trace("恢复上次考试数据成功");
                }
                catch (Exception ex)
                {
                    ELogger.Error(string.Format("数据反序列化失败！{0}", ex.Message));
                    ELogger.Error(string.Format("数据反序列化失败！{0}", ex.StackTrace));
                    bNeedResume = false;
                }
            }
            if (bNeedResume)
            {
                if (DialogResult.OK == MessageBox.Show(string.Format("系统检测到上次考试未正常结束，是否继续上次考试？\n考试时间：{0}\n班级信息：{1}\n考试信息：{2}", Program.MTInfo.MicroTestDate.ToString("yyyy-MM-dd"), Program.MTInfo.MicroTestRoomInfo, Program.MTInfo.MicroTestTitle),
                    "注意", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
                {
                    bNeedResume = true;
                    ELogger.Trace("用户选择继续上次考试！");
                }
                else
                {
                    bNeedResume = false;
                    File.Delete(dataFile);
                    ELogger.Trace("用户选择不再继续上次考试！删除数据文件！");
                }
            }
            if (bNeedResume)
            {
                Program.TEST_KEY = Program.MTInfo.MicroTestID;
                string folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\WiseClass";

                if (!Directory.Exists(folder))
                    Directory.CreateDirectory(folder);
                string dateStr = Program.MTInfo.MicroTestDate.ToString("yyyy-MM-dd");
                folder = folder + "\\" + dateStr;
                if (!Directory.Exists(folder))
                    Directory.CreateDirectory(folder);
                Program.DATA_ROOT = folder;
                folder = folder + "\\" + Program.TEST_KEY;
                if (!Directory.Exists(folder))
                    Directory.CreateDirectory(folder);
                Program.DATA_FOLDER = folder;
                ELogger.Trace(string.Format("微测密钥:{0}", Program.TEST_KEY));
                ELogger.Trace(string.Format("微测数据存储路径:{0}", Program.DATA_FOLDER));

            }
            return bNeedResume;
        }

        /// <summary>
        /// 恢复上课数据
        /// </summary>
        /// <returns></returns>
        private bool ResumeClassData()
        {
            string dataFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WiseClass\\class.dat";
            bool bNeedResume = false;
            if (File.Exists(dataFile))
            {
                try
                {
                    //Program.CurrentClassInfo = SerializeHelper.DeserialData<ClassInfo>(dataFile);
                    ClassInfo cli = SerializeHelper.DeserialData<ClassInfo>(dataFile);

                    if (cli==null||Program.CurrentClassInfo.ClassRoomInfo != cli.ClassRoomInfo)
                    {
                        return false;
                    }
                    Program.CurrentClassInfo = SerializeHelper.DeserialData<ClassInfo>(dataFile);
                    bNeedResume = true;
                    ELogger.Trace(string.Format("恢复上次上课数据 班级信息：{0} 课件信息：{1}", Program.CurrentClassInfo.ClassRoomInfo, Program.CurrentClassInfo.ClassSymTitle));
                    for (int i = 0; i < Program.CurrentClassInfo.CardList.Count; i++)
                    {
                        ELogger.Trace(string.Format("恢复学生名单 学生{0}：{1}", i + 1, Program.CurrentClassInfo.CardList[i].Name));
                    }

                    ELogger.Trace("恢复上次考试数据成功");
                }
                catch (Exception ex)
                {
                    ELogger.Error(string.Format("数据反序列化失败！{0}", ex.Message));
                    ELogger.Error(string.Format("数据反序列化失败！{0}", ex.StackTrace));
                    bNeedResume = false;
                }

            }
            if (bNeedResume)
            {
                if (DialogResult.OK == MessageBox.Show(string.Format("系统检测到上次软件异常退出，是否继续上次课程？\n班级信息：{0}\n课件信息：{1}", Program.CurrentClassInfo.ClassRoomInfo, Program.CurrentClassInfo.ClassSymTitle),
                "注意", MessageBoxButtons.OKCancel, MessageBoxIcon.Information))
                {
                    bNeedResume = true;
                    File.Delete(dataFile);
                    ELogger.Trace("用户选择继续上次课程！");
                }
                else
                {
                    bNeedResume = false;
                    File.Delete(dataFile);
                    ELogger.Trace("用户选择不再继续上次课程！删除课程文件！");
                }
            }
            
            return bNeedResume;
        }
        private void DigitalPen_PenConnected(ulong time, string penSerial, int penType)
        {
            switch (enterSceneType)
            {
                case SceneType.Scene_Class:
                    frmClass.DigitalPen_PenConnected(time, penSerial, penType);
                    break;
                case SceneType.Scene_Exam:
                        frmExam.DigitalPen_PenConnected(time, penSerial, penType);
                    break;
                case SceneType.Scene_Prepare:
                case SceneType.Scene_ExamPrepare://考试未检测名单，进入绑定
                case SceneType.Scene_ClassPrepare:
                        frmPrepare.DigitalPen_PenConnected(time, penSerial, penType);

                    break;
                default:
                    break;
            }
        }
        private void DigitalPen_PenDisconnect(ulong time, string penSerial, int penType)
        {
            switch (enterSceneType)
            {
                case SceneType.Scene_Class:
                    frmClass.DigitalPen_PenDisconnect(time, penSerial, penType);

                    break;
                case SceneType.Scene_Exam:
                    frmExam.DigitalPen_PenDisconnect(time, penSerial, penType);
                    break;
                case SceneType.Scene_Prepare:
                case SceneType.Scene_ExamPrepare:
                case SceneType.Scene_ClassPrepare:

                    frmPrepare.DigitalPen_PenDisconnect(time, penSerial, penType);

                    break;
                default:
                    break;
            }
        }
        private void DigitalPen_PenCoordinate(ulong time, string penSerial, int penType, string pageSerial, ulong pageId, int cx, int cy, byte force)
        {
            switch (enterSceneType)
            {
                case SceneType.Scene_Class:
                    frmClass.DigitalPen_PenCoordinate(time, penSerial, penType, pageSerial, pageId, cx, cy, force);

                    break;
                case SceneType.Scene_Exam:
                    frmExam.DigitalPen_PenCoordinate(time, penSerial, penType,pageSerial,pageId,cx,cy,force);
                    break;
                case SceneType.Scene_Prepare:
                case SceneType.Scene_ExamPrepare:
                case SceneType.Scene_ClassPrepare:

                    frmPrepare.DigitalPen_PenCoordinate(time, penSerial, penType, pageSerial, pageId, cx, cy, force);

                    break;
                default:
                    break;
            }
        }
        private void DigitalPen_PenDown(ulong time, string penSerial, int penType)
        {
            switch (enterSceneType)
            {
                case SceneType.Scene_Class:
                    frmClass.DigitalPen_PenDown(time, penSerial, penType);

                    break;
                case SceneType.Scene_Exam:
                    frmExam.DigitalPen_PenDown(time, penSerial, penType);
                    break;
                case SceneType.Scene_Prepare:
                case SceneType.Scene_ExamPrepare:
                case SceneType.Scene_ClassPrepare:

                    frmPrepare.DigitalPen_PenDown(time, penSerial, penType);

                    break;
                default:
                    break;
            }
        }
        private void DigitalPen_PenUp(ulong time, string penSerial, int penType)
        {
            switch (enterSceneType)
            {
                case SceneType.Scene_Class:
                    frmClass.DigitalPen_PenUp(time, penSerial, penType);

                    break;
                case SceneType.Scene_Exam:
                    frmExam.DigitalPen_PenUp(time, penSerial, penType);
                    break;
                case SceneType.Scene_Prepare:
                case SceneType.Scene_ExamPrepare:
                case SceneType.Scene_ClassPrepare:
                    frmPrepare.DigitalPen_PenUp(time, penSerial, penType);

                    break;
                default:
                    break;
            }
        }
        public void SaveDataWhenExcetionAccurs()
        {
            try
            {
                switch (enterSceneType)
                {
                    case SceneType.Scene_Class:
                        frmClass.SaveCurrentDrawingImageWhenExcpetion();
                        break;
                    case SceneType.Scene_Exam:
                        frmExam.SaveCurrentDrawingImageWhenExcpetion();
                        break;
                    case SceneType.Scene_Prepare:
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {

                
            }
            
        }

    }
}
